package util

import (
	"TODecider/src/logger"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"regexp"
	"time"
)

// ObtainHostIPBy requests the master node for real host IP address
func ObtainHostIPBy(url string) string {
	result := RequestHttp(url)
	if !IsLegalIP(result) {
		panic(errors.New(fmt.Sprintf("invalid response content: %s", result)))
	}
	return result
}

// RequestHttp finishes HTTP request with certain URL
func RequestHttp(url string) string {
	client := &http.Client{Timeout: 10 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		panic(errors.New(fmt.Sprintf("client timeout: %s", err.Error())))
	}
	defer resp.Body.Close()
	result, _ := ioutil.ReadAll(resp.Body)
	return string(result)
}

// MakeSlicesFloat64 makes a two-dimensional array slice
func MakeSlicesFloat64(r int, c int) [][]float64 {
	arr := make([][]float64, r)
	for i := range arr {
		arr[i] = make([]float64, c)
	}
	return arr
}

// IsLegalIP determines whether the string is an available IP address
func IsLegalIP(s string) bool {
	ipReg := "((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}"
	r, _ := regexp.Compile(ipReg)
	return r.MatchString(s)
}

// PrintTOEvaluation prints the result of task offloading decision
func PrintTOEvaluation(m map[int]int, f float64, i int, d int) {
	log := logger.GetLogger()
	log.Debugf("[TO Evaluation] Task offloading decision map: %s", PrintMap(m))
	log.Debugf("[TO Evaluation] Total cost: %f", f)
	log.Debugf("[TO Evaluation] Total iterations: %d times", i)
	log.Debugf("[TO Evaluation] Execution duration: %d ms", d)
}

// PrintMap prints key-value pairs
func PrintMap(m map[int]int) string {
	var s string
	for val := range m {
		s += fmt.Sprintf("(%d, %d)", val, m[val])
	}
	return s
}
